package com.tc.base.dao;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import javax.persistence.Id;

public class DynamicUpdate {

	
	
	
	public String invokeReflectToHql(Object object) throws Exception{
		Class<?> clazz = object.getClass();
		String primaryKey = primaryKey(clazz);
		
		String hql = "";
		String setString = "";
		String whereString = "";
		
		
		
		if(object != null){
			String clazzName = clazz.getName().replaceAll("\\w+\\.+", "");
			String objectName = fristLetterToLowerCase(clazzName);
			hql = "update " + clazzName + " " + objectName + " " + "set  ";
			Field[] field = clazz.getDeclaredFields();
			
			for(Field f : field){
				String colunmName = f.getName();
				if(!colunmName.equals(primaryKey)){
					String methodName = filedNameToMethodName(colunmName);
					Method m = clazz.getMethod(methodName);
					Object value = m.invoke(object);
					if(value != null){
						setString = setString + ", " + objectName + "." + colunmName + "='" + value + "' ";
					}
				}
			}
			setString = setString.substring(1);		
			Method m = clazz.getMethod(filedNameToMethodName(primaryKey));			
			Object primaryKeyValue = m.invoke(object);
			whereString = "where " + objectName + "." + primaryKey + "='" + primaryKeyValue + "'";
		}
		
		hql = hql + setString + whereString;
		System.out.println("HQL:" + hql);
		return hql;
	}
	
	
	
	public String primaryKey(Class<?> clazz){
		Method[] method =clazz.getMethods();
		String primaryKey = null;
		for(Method m : method){
			Id annotationId = m.getAnnotation(Id.class);
			if(annotationId != null){
				primaryKey = methodNameToFiledName(m.getName());
				break;
			}
		}
		Field[] field = clazz.getDeclaredFields();
		for(Field f : field){
			Id annotationId = f.getAnnotation(Id.class);
			if(annotationId != null){
				primaryKey = f.getName();
				break;
			}
		}
		return primaryKey;
	}
	
	
	
	public String methodNameToFiledName(String methodName){
		methodName = methodName.substring(3,methodName.length());
		methodName = methodName.substring(0,1).toLowerCase() + methodName.substring(1,methodName.length());
		return methodName;
	}
	
	public String filedNameToMethodName(String filedName){
		filedName = filedName.substring(0,1).toUpperCase() + filedName.substring(1,filedName.length());
		filedName = "get" + filedName;
		return filedName;
	}
	
	public String fristLetterToLowerCase(String string){
		string = string.substring(0,1).toLowerCase() + string.substring(1,string.length());
		return string;
	}
	
	public String fristLetterToUpperCase(String string){
		string = string.substring(0,1).toUpperCase() + string.substring(1,string.length());
		return string;
	}
}
